import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:date_format/date_format.dart';
import 'package:toast/toast.dart';

class CarshouxuPage extends StatefulWidget {
  final String oid;
  final Map formalities;
  final int type;
  CarshouxuPage(this.oid, this.formalities,this.type);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid, formalities,type);
}

class _MyHomePageState extends State<CarshouxuPage> {
  List formList;
  final String oid;
  final Map formalities;
  final int type;
  String invoice = "1"; //购车发票
  String Tax = "1"; //购置税
  String Status = "";
  _MyHomePageState(this.oid, this.formalities,this.type);
  initState() {
    super.initState();
    formList = [
      {
        "title": '购车发票/过户票',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "value": "有",
        "code": "invoice"
      },
      {
        "title": '购置税证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "Tax",
        "value": "有"
      },
      {
        "title": '行驶证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "vehicle",
        "value": "有"
      },
      {
        "title": '年检有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "yearcheck_e_time",
        "value": "请选择日期"
      },
      {
        "title": '登记证',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "registration",
        "value": "有"
      },
      {
        "title": '过户次数',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "transfer",
        "value": ""
      },
      {
        "title": '交强险有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "compu_e_time",
        "value": "请选择日期"
      },
      {
        "title": '交强险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "compu_name",
        "value": ""
      },
      {
        "title": '车船税有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "vehicles_e_time",
        "value": "请选择日期"
      },
      // {
      //   "title": '车船险随车出售',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "3",
      //   "code": "vehicles",
      //   "value": "是"
      // },
      {
        "title": '商业险金额',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_price",
        "value": ""
      },
      {
        "title": '商业险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_name",
        "value": ""
      },
    ];
    loaddata();
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;

String api = HttpHelper.API_OrderDetail;
if(type==2)api=HttpHelper.API_BussinessOrderDetail;
    HttpHelper.post(api, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          // for (var i = 0; i < oldlist.length; i++) {
          //   var item = oldlist[i];
          //   var str = "";
          //   if (i == 0)
          //     str = orderinfo["name"];
          //   else if (i == 1)
          //     str = orderinfo["phone_num"];
          //   else if (i == 2)
          //     str = orderinfo["name"];
          //   else if (i == 3)
          //     str = orderinfo["phone_num"];
          //   else if (i == 4)
          //     str = orderinfo["add_time"];
          //   else
          //     str = orderinfo["address"];

          //   item["sub_title"] = str;
          // }

          setState(() {
            formList = oldlist;
            Status = orderinfo["status"].toString();
            // orders=data["info"];
          });
          if (Status != "0"&&Status != "1") {
          Map foemlitile =
              data["info"]["inspectorItemsResult"]["formalities"];
           
            var templist = formList;
            print('数据重组');
            print(foemlitile);
            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];
              print(code);

              templist[i]["value"] = foemlitile[code];
              if (code == "vehicles") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
              if (code == "business_sell_by_car") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
            }
            setState(() {
              formList=templist;
            });
            print(formList);
          }
          else{
            
            var templist = formList;
            var listvalue = this.formalities;
            print(this.formalities);
            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];
              print(code);
              print(this.formalities[code]);
              
             // this.formalities[code]=formList[i]["value"];
              formList[i]["value"]=this.formalities[code]==""?formList[i]["value"]:this.formalities[code];
             
            }
             setState(() {
              formList=formList;
            });
            print(formList);
          }
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  Widget itemContent(item) {
    var child;
    if (item["type"] == "0") {
      child = 
      Padding(padding:new EdgeInsets.fromLTRB(0, 0, 10, 0),
      child:
      Row(
        // crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Radio<String>(
              //当前Radio的值
              hoverColor: Color.fromRGBO(200, 200, 200, 1),
              focusColor: Color.fromRGBO(25, 172, 249, 1),
              value: "有",
              activeColor: Color.fromRGBO(25, 172, 249, 1),
              groupValue: item["value"],
              // groupValue: defaultv,
              onChanged: (value) {
                String code = item["code"];
               // String code = item["code"];
           
                setState(() {
                  item["value"] = value;
                  formalities[code] = value;
                  // paytype = value;
                });
              }),
          new Text("有",
              style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
          Radio<String>(
              //当前Radio的值
              hoverColor: Color.fromRGBO(200, 200, 200, 1),
              focusColor: Color.fromRGBO(25, 172, 249, 1),
              value: "无",
              activeColor: Color.fromRGBO(25, 172, 249, 1),
              groupValue: item["value"],
              // groupValue: defaultv,
              onChanged: (value) {
               // String code = item["code"];
                String code = item["code"];
            // item["value"] = value;
            // formalities[code] = value;
                setState(() {
                  item["value"] = value;
                  formalities[code] = value;
                });
              }),
          new Text("无",
              style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
        ],
      ));
    } else if (item["type"] == "1") {
      DateTime initialDate = DateTime.now();
      child = 
      Padding(padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
      child:
      Align(
          alignment: Alignment.centerRight,
          
          child: new GestureDetector(
              child: new Text(item["value"]),
              onTap: () async {
                final DateTime dateTime = await showDatePicker(
                  context: context,
                  //定义控件打开时默认选择日期
                  initialDate: initialDate,
                  //定义控件最早可以选择的日期
                  firstDate: DateTime(2018, 1),
                  //定义控件最晚可以选择的日期
                  lastDate: DateTime(2050, 1),
                  //locale: Locale.fromSubtags(languageCode: 'zh'),
                  // builder: (BuildContext context, Widget child) {
                  //   return Theme(
                  //     data: CommonColors.themData,
                  //     child: child,
                  //   );
                  // },
                );
                // Locale myLocale = Localizations.localeOf(context);
                // final DateTime picker = await showDatePicker(
                //     context: context,
                //     initialDate: DateTime.now(),
                //     firstDate: DateTime(2016),
                //     lastDate: DateTime(2019),
                //     locale: myLocale);
                // setState(() {
                //   item["value"] = picker.toString();
                // });
                if (dateTime != null) {
                  setState(() {
                    String code = item["code"];
                    item["value"] =
                        formatDate(dateTime, [yyyy, "-", mm, "-", dd]);
                    formalities[code] = item["value"];
                  });
                }
              })));
    } else if (item["type"] == "2") {
      child = new TextField(
          onChanged: (value) {
            
            String code = item["code"];
            item["value"] = value;
            formalities[code] = value;
          },
          textAlign: TextAlign.right,
          //controller: _validtroller,
          decoration: InputDecoration(
              hintText: item["value"]==""?'请填写信息':item["value"],
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
              )));
    } else if (item["type"] == "3") {
      child = Switch(
        //当前状态
        value: item["value"]=="是"?true:false,
        // 激活时原点颜色
        activeColor: Colors.blue,
        inactiveTrackColor: Colors.blue.shade50,
        onChanged: (value) {
          //重新构建页面
          setState(() {
            String code = item["code"];
            item["value"] = value==true?"是":"否";
            formalities[code] = value;
          });
        },
      );
    }

    if (item["type"] == "3") {
      return new Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child);
    } else {
      return Expanded(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child));
    }
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in formList) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
              color: Colors.white,
              height: 50,
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: Align(
                              alignment: Alignment.centerLeft,
                              child: new Text(
                                item['title'],
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Color.fromRGBO(102, 102, 102, 1)),
                              )))),
                  Status == "0"||Status == "1"
                      ? itemContent(item)
                      : Expanded(child:
                       Padding(padding: new EdgeInsets.fromLTRB(0, 0, 15, 0),child:
                      Align(
                        
                        alignment: Alignment.centerRight,
                        child:
                      new Text(item["value"]))))
                  // Expanded(
                  //   child: new Padding(
                  //       padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                  //       child: new TextField(
                  //           textAlign: TextAlign.right,
                  //           //controller: _validtroller,
                  //           decoration: InputDecoration(
                  //             hintText: '验证码',
                  //             border: OutlineInputBorder(
                  //               borderSide: BorderSide.none,
                  //             ),
                  //           ))),
                  // child: new Text(
                  //   item['sub_title'],
                  //   style:
                  //       TextStyle(fontSize: 15, color: item['sub_color']),
                  // )),
                  //)
                ],
              ))));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('手续信息'),
          backgroundColor: Colors.white,
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
          decoration: new BoxDecoration(
            color: Color.fromRGBO(238, 238, 238, 1),
          ),
          child: Padding(
              padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
              child: new ListView(
                children: <Widget>[buildcontent()],
              )),
        )));
    // if(Status == "0"){return WillPopScope(
    //   child:
    //    new Scaffold(
    //     appBar: new AppBar(
    //       title: new Text('手续信息'),
    //       backgroundColor: Colors.white,
    //       iconTheme: new IconThemeData(color: Colors.black),
    //       elevation: 0,
    //       // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
    //     ),
    //     body: new Center(
    //         child: Container(
    //       decoration: new BoxDecoration(
    //         color: Color.fromRGBO(238, 238, 238, 1),
    //       ),
    //       child: Padding(
    //           padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
    //           child: new ListView(
    //             children: <Widget>[buildcontent()],
    //           )),
    //     )))
    //     ,onWillPop: () => willpop());
    //     }else{
        
    //     return new Scaffold(
    //     appBar: new AppBar(
    //       title: new Text('手续信息'),
    //       backgroundColor: Colors.white,
    //       iconTheme: new IconThemeData(color: Colors.black),
    //       elevation: 0,
    //       // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
    //     ),
    //     body: new Center(
    //         child: Container(
    //       decoration: new BoxDecoration(
    //         color: Color.fromRGBO(238, 238, 238, 1),
    //       ),
    //       child: Padding(
    //           padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
    //           child: new ListView(
    //             children: <Widget>[buildcontent()],
    //           )),
    //     )));
    //     }
  }
  Future<bool> willpop() {
    _showDialog();
    return Future.value(false);
  }
  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('是否保存信息?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.pop(context);
                   // Navigator.pop(this.context);
                   // Navigator.of(context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () async{
                    SharedPreferences pref = await SharedPreferences.getInstance();
                    pref.setBool('shouxusave', true);
                    Navigator.pop(this.context);
                    // Navigator.of(context).pop();
                    // saveandpop();
                    // sleep(Duration(seconds:1));
                    // //sleep(Duration(seconds: 1));
                     Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
 void saveandpop()async{
    LoadingPage loadpage = new LoadingPage(context);
    loadpage.show();
    sleep(Duration(seconds: 1));
    Navigator.pop(context);

  }
}
